package com.agent.platform.entity;

import jakarta.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.annotations.JdbcTypeCode;
import org.hibernate.type.SqlTypes;

import java.time.LocalDateTime;
import java.util.Map;

/**
 * Agent实体 - 对应Node.js版本的Agent配置
 */
@Entity
@Table(name = "agents")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Agent {

    @Id
    @Column(name = "agent_id", length = 255)
    private String agentId;

    @Column(name = "context_manager_url", length = 500)
    private String contextManagerUrl;

    @Column(name = "tool_manager_url", length = 500)
    private String toolManagerUrl;

    @Column(name = "model_selector_url", length = 500)
    private String modelSelectorUrl;

    /**
     * 控制配置 - JSON格式存储
     */
    @JdbcTypeCode(SqlTypes.JSON)
    @Column(name = "control_config", length = 4000)
    private Map<String, Object> controlConfig;

    /**
     * 元数据 - JSON格式存储
     */
    @JdbcTypeCode(SqlTypes.JSON)
    @Column(name = "metadata", length = 4000)
    private Map<String, Object> metadata;

    @Column(name = "status", length = 50)
    private String status = "active"; // active, inactive, deleted

    @Column(name = "created_at")
    private LocalDateTime createdAt;

    @Column(name = "updated_at")
    private LocalDateTime updatedAt;

    @PrePersist
    protected void onCreate() {
        createdAt = LocalDateTime.now();
        updatedAt = LocalDateTime.now();
    }

    @PreUpdate
    protected void onUpdate() {
        updatedAt = LocalDateTime.now();
    }

    // 辅助方法：获取控制配置值
    public Object getControlConfigValue(String key, Object defaultValue) {
        if (controlConfig == null) {
            return defaultValue;
        }
        return controlConfig.getOrDefault(key, defaultValue);
    }

    public Integer getMaxSteps() {
        return (Integer) getControlConfigValue("maxSteps", 50);
    }

    public Integer getMaxFailures() {
        return (Integer) getControlConfigValue("maxFailures", 3);
    }

    public Long getMaxExecutionTime() {
        Object value = getControlConfigValue("maxExecutionTime", 300000);
        if (value instanceof Integer) {
            return ((Integer) value).longValue();
        }
        return (Long) value;
    }

    public Boolean isToolUsageEnabled() {
        return (Boolean) getControlConfigValue("enableToolUsage", true);
    }
}
